<template>
  <div class="question-form">
    <div class="question-form-inner">
      <!-- 题目类型 -->
      <mu-sub-header>题目类型</mu-sub-header>
      <div class="question-form-item-box">
        <type-select v-model="form.type_id" />
      </div>

      <!-- 形式选择 -->
      <mu-sub-header>题目形式</mu-sub-header>
      <div class="form-style question-form-item-box">
        <mu-radio v-model="form.style" class="form-style-item" :value="0" label="选择题"></mu-radio>
        <mu-radio v-model="form.style" class="form-style-item" :value="1" label="填空题"></mu-radio>
      </div>

      <!-- 题干 -->
      <mu-sub-header>题干</mu-sub-header>
      <div class="question-form-item-box">
        <mu-text-field v-model="form.text" class="input-low-padding" full-width placeholder="请在这里输入题干" multi-line :rows="1" :rows-max="3"></mu-text-field>
      </div>

      <!-- 图片 -->
      <mu-sub-header>图片</mu-sub-header>
      <div class="question-form-item-box">
        <image-input v-model="form.image" />
      </div>

      <!-- 选项 -->
      <div v-if="form.style === 0">
        <mu-sub-header>选项</mu-sub-header>
        <options-input ref="optionsInput" v-model="form.options" class="question-form-item-box" />
      </div>

      <!-- 答案 -->
      <mu-sub-header>答案</mu-sub-header>
      <div class="question-form-item-box">
        <mu-text-field v-if="form.style === 1" v-model="form.answer" full-width placeholder="请在这里输入答案" multi-line :rows="1" :rows-max="3" class="input-low-padding"></mu-text-field>
        <answer-select v-else v-model="form.answer" :options="form.options" />
      </div>

      <!-- 错误信息 -->
      <ul class="error-list mu-error-color">
        <li v-for="msg in validErrors" :key="msg" class="error-item">{{ msg }}</li>
      </ul>
      <ul class="warning-list">
        <li v-for="msg in validWarnings" :key="msg" class="warning-item">{{ msg }}</li>
      </ul>

      <!-- 预览/提交 -->
      <div class="action-box">
        <mu-button v-if="qcConfig.preview" full-width color="success" @click="showPreview()">查看预览</mu-button>
        <mu-button v-else full-width :color="submitButtonInfo.color" @click="submit()">{{ submitButtonInfo.text }}</mu-button>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from 'vuex'
import { isQuestionInputValid } from '@/util/validate'
import TypeSelect from '@/components/TypeSelect'
import OptionsInput from '@/components/OptionsInput'
import AnswerSelect from '@/components/AnswerSelect'
import ImageInput from '@/components/ImageInput'
import { convertCreateQuestionStatusToButtonInfo } from '@/util'
import { submitQuestion } from '@/mixins'

export default {
  name: 'QuestionForm',
  components: {
    TypeSelect,
    AnswerSelect,
    ImageInput,
    OptionsInput
  },
  mixins: [
    submitQuestion
  ],
  props: {
    modified: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      form: {
        type_id: 0,
        style: 0,
        image: null,
        text: '',
        options: [],
        answer: ''
      },
      validErrors: [],
      validWarnings: [],
      commit: 0,
      last: '',
      status: {
        id: 0,
        submitting: false,
        question: false,
        image: false
      }
    }
  },
  computed: {
    ...mapGetters({
      types: 'types',
      qcConfig: 'questionCreateConfig'
    }),
    formJson() {
      return JSON.stringify(this.form)
    },
    lastEqaulsForm() {
      return this.last !== this.formJson
    },
    submitButtonInfo() {
      return convertCreateQuestionStatusToButtonInfo(this.status)
    }
  },
  watch: {
    formJson() {
      this.commit = 0
    },
    lastEqaulsForm(val) {
      this.$emit('update:modified', val)
    }
  },
  created() {
    this.clearForm()
  },
  methods: {
    ...mapMutations({
      setQcConfig: 'SET_QUESTION_CREATE_CONFIG',
      setQcForm: 'SET_QUESTION_CREATE_FORM'
    }),
    // 清空表单
    clearForm() {
      const n = this.qcConfig.option_count
      this.form.type_id = this.qcConfig.type_id
      this.form.style = this.qcConfig.style
      this.form.options = Array(n).fill('')
      this.form.image = null
      this.form.text = ''
      this.form.answer = ''
      this.last = JSON.stringify(this.form)
    },
    // 清空状态
    clearStatus() {
      this.status = {
        id: 0,
        submitting: false,
        question: false,
        image: false
      }
    },
    // 查看预览
    showPreview() {
      this.updateQcConfig()
      if (this.checkValid() === true) {
        this.last = JSON.stringify(this.form)
        this.updateQcForm()
        this.$nextTick(() => {
          this.$router.push({ name: 'question-create-preview' })
        })
      }
    },
    // 提交题目
    async submit() {
      if (await this.submitQuestion()) {
        this.clearForm()
        this.clearStatus()
      }
    },
    // 检查输入是否有效
    checkValid() {
      // 各种判断
      const { errors, warnings } = isQuestionInputValid(this.form)
      this.validErrors = errors
      this.validWarnings = warnings
      if (errors.length > 0) {
        this.$toast.error('题目存在错误，不能提交')
      } else if (warnings.length > 0 && this.commit === 0) {
        this.$toast.warning('题目可能存在问题，仍要继续请再次点击“查看预览”')
      }
      const isValid = (errors.length === 0 && warnings.length === 0) || (errors.length === 0 && this.commit >= 1)
      // 记录尝试一次
      if (isValid) {
        this.commit = 0
      } else {
        this.commit++
      }
      return isValid
    },
    // 更新QcConfig
    updateQcConfig() {
      const config = { ...this.qcConfig }
      config.type_id = this.form.type_id
      config.style = this.form.style
      if (this.form.style === 0) {
        config.option_count = this.form.options.length
      }
      this.setQcConfig(config)
    },
    // 刷新QcForm
    updateQcForm() {
      const form = { ...this.form }
      if (form.style === 1) {
        form.options = []
      }
      this.setQcForm(form)
    }
  }
}
</script>

<style>
.question-form .question-form-item-box {
  border: 1px solid #aaa;
  padding: 3px 6px;
  border-radius: 3px;
}
.question-form .input-low-padding {
  padding-bottom: 8px;
  margin-bottom: 0;
  min-height: 24px;
}
</style>

<style scoped>
.question-form {
  padding: 12px;
}
.question-form-inner {
  margin: 0 auto;
  width: 600px;
}
.form-style {
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
}
.form-style-item {
  margin: 8px;
}

.error-list,
.warning-list {
  list-style: none;
  color: #fff;
}
.error-list {
  margin-top: 12px;
}
.warning-list {
  background-color: #fb8c00;
}
.error-item,
.warning-item {
  padding: 6px 9px;
}
.action-box {
  margin-top: 12px;
}

.is-phone .question-form-inner {
  width: 100%;
}
</style>
